﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using SyncConfig.Dialog;
using Microsoft.Synchronization;
using DevComponents.AdvTree;
using DevComponents.DotNetBar.Controls;
using System.IO;
using AppCommon.Controls;
using AppCommon;
using DevComponents.DotNetBar.SuperGrid;

namespace SyncConfig.Controls
{
    public partial class AddScopeInfoEx : UserControlBase
    {
        DataTable tblScopeType = new DataTable();
        DataTable tblDirection = new DataTable();

        public AddScopeInfoEx()
        {
            InitializeComponent();
            FixClientId = Guid.Empty;
            if (!DesignMode)
            {
                tblScopeType.Columns.Add("ID", typeof(int));
                tblScopeType.Columns.Add("Name", typeof(string));

                tblScopeType.Rows.Add(1, "Danh mục");
                tblScopeType.Rows.Add(2, "Phiếu");
                cbScopeType.DisplayMember = "Name";
                cbScopeType.ValueMember = "ID";
                cbScopeType.DataSource = tblScopeType;
                tblDirection.Columns.Add("Direction");
                tblDirection.Columns.Add("Name");
                tblDirection.Rows.Add("Undefine", "Chưa chọn");
                tblDirection.Rows.Add(SyncDirectionOrder.DownloadAndUpload.ToString(), "DownloadAndUpload");
                tblDirection.Rows.Add(SyncDirectionOrder.UploadAndDownload.ToString(), "UploadAndDownload");
                tblDirection.Rows.Add(SyncDirectionOrder.Download.ToString(), "DownloadOnly");
                tblDirection.Rows.Add(SyncDirectionOrder.Upload.ToString(), "UploadOnly");
                cbDirection.DisplayMember = "Name";
                cbDirection.ValueMember = "Direction";
                cbDirection.DataSource = new DataView(tblDirection);
                GridColumn col = gridClient.PrimaryGrid.Columns["Direction"];
                GridComboBoxExEditControl combox = (GridComboBoxExEditControl)col.RenderControl;
                DataView view= new DataView(tblDirection);
                combox.DisplayMember = "Name";
                combox.ValueMember = "Direction";
                combox.DataSource = view;
                //combox.CellEditMode = CellEditMode.InPlace;
                combox = (GridComboBoxExEditControl)col.EditControl;
                combox.DisplayMember = "Name";
                combox.ValueMember = "Direction";
                combox.DataSource = view;
            }
        }
        public Guid FixClientId { get; set; }
        public void BindingNew(Node node)
        {
            SyncConfigDS.ClientRow clientRow = node.Tag as SyncConfigDS.ClientRow;

            if (clientRow != null)
                FixClientId = clientRow.ClientId;
            errorProvider1.Clear();
            CurrentNode = node;

            txtScopeName.Text = "";
            txtSchema.Text = "";
            txtComment.Text = "";
            cbDirection.SelectedIndex = 0;

            cbScopeType.SelectedIndex = -1;

            txtServerAssembly.Text = "";
            txtServerClassPath.Text = "";
            txtClientAssembly.Text = "";
            txtClientClassPath.Text = "";
            txtScopeVersion.Value = 1;
            txtSchemaVersion.Value = 1;
            txtAssemblyVersion.Value = 1;
            LoadClient(Guid.Empty);

        }
        private void LoadClient(Guid scopeId)
        {
            //SyncConfigDS.ScopeInfoExRow Scope = CurrentNode.Tag as SyncConfigDS.ScopeInfoExRow;
            SyncConfigDS.ClientConfigDataTable tblConfig = FrmMain.MainForm.TreeManipulation.dsSyncConfig.ClientConfig;

            DataView view = new DataView(tblConfig);
            view.RowFilter = "ScopeExId='" + scopeId.ToString() + "'";
            view.Sort = "ClientId";
            SyncConfigDS.ClientDataTable tblClient = FrmMain.MainForm.TreeManipulation.dsSyncConfig.Client;
            for (int i = 0; i < tblClient.Count; i++)
            {
                SyncConfigDS.ClientRow clienRow = tblClient[i];
                if (clienRow.ClientId.Equals(Guid.Empty))
                    continue;
                if (view.Find(clienRow.ClientId) < 0)
                {
                    SyncConfigDS.ClientConfigRow newConfig = tblConfig.NewClientConfigRow();
                    newConfig.ClientId = clienRow.ClientId;
                    newConfig.ScopeExId = scopeId;
                    newConfig.ClientName = clienRow.ClientName;
                    newConfig.Des = clienRow.IsDesNull() ? "" : clienRow.Des;
                    newConfig.AssemblyVersion = 1;
                    newConfig.ScopeVersion = 1;
                    newConfig.SchemaVersion = 1;
                    newConfig.LogLocation = "nothing";
                    newConfig.BatchSize = 0;
                    tblConfig.AddClientConfigRow(newConfig);

                }
            }
            gridClient.PrimaryGrid.DataSource = view;
        }
        public override void Close()
        {
            CurrentNode = null;
            //  tblScopeType.Dispose();
            base.Close();
        }
        public void BindingInfo(Node node)
        {
            errorProvider1.Clear();
            CurrentNode = node;

            SyncConfigDS.ScopeInfoExRow Scope = node.Tag as SyncConfigDS.ScopeInfoExRow;

            txtScopeName.Text = Scope.IsScopeNameNull() ? "" : Scope.ScopeName;
            txtSchema.Text = Scope.IsSchemaNull() ? "" : Scope.Schema;
            txtComment.Text = Scope.IsCommentNull() ? "" : Scope.Comment;
            cbDirection.SelectedValue = Scope.Direction;

            cbScopeType.SelectedValue = Scope.ScopeType;

            txtServerAssembly.Text = Scope.IsServerAssemblyNull() ? "" : Scope.ServerAssembly;
            txtServerClassPath.Text = Scope.IsServerClassNull() ? "" : Scope.ServerClass;
            txtClientAssembly.Text = Scope.IsClientAssemblyNull() ? "" : Scope.ClientAssembly;
            txtClientClassPath.Text = Scope.IsClientClassNull() ? "" : Scope.ClientClass;
            txtScopeVersion.Value = Scope.ScopeVersion;
            txtSchemaVersion.Value = Scope.SchemaVersion;
            txtAssemblyVersion.Value = Scope.AssemblyVersion;
            txtTemplate.Text = Scope.IsTemplateNameNull() ? "" : Scope.TemplateName;
            LoadClient(Scope.ScopeExId);
            //if (cbClient.DataSource == null)
            //{
            //    cbClient.DataSource = FrmMain.MainForm.TreeManipulation.dsSyncConfig.Client;
            //    cbClient.DisplayMembers = "ClientName;Des";
            //    cbClient.ValueMember = "ClientId";
            //}
        }
        public bool IsCommon
        {
            set
            {
                // ckIsCommon.Checked = value;
            }
            get
            {// return ckIsCommon.Checked; 
                return false;
            }
        }

        private void txtScopeName_ButtonCustomClick(object sender, EventArgs e)
        {
            PickScope frm = new PickScope();
            try
            {
                frm.ShowDialog();
                if (frm.DialogResult == DialogResult.OK)
                {
                    txtScopeName.Text = frm.SelectedRow["Name"].ToString();
                    txtSchema.Text = frm.SelectedRow["Schema"].ToString();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                frm.Dispose();
            }
        }

        private void btnLuu_Click(object sender, EventArgs e)
        {


            // ckIsCommon.Enabled = false;
            errorProvider1.Clear();
            errorProvider1.Tag = null;

            if (string.IsNullOrEmpty(txtScopeName.Text))
            {
                errorProvider1.SetError(txtScopeName, "Chưa chọn scope");
                errorProvider1.Tag = 1;
            }
            if (string.IsNullOrEmpty(txtSchema.Text.Trim()))
            {
                errorProvider1.SetIconAlignment(txtSchema, ErrorIconAlignment.MiddleLeft);
                errorProvider1.SetError(txtSchema, "Chưa nhập schema");
                errorProvider1.Tag = 1;
            }
            if (cbDirection.SelectedIndex < 1)
            {

                errorProvider1.SetError(cbDirection, "Chưa chọn hướng đồng bộ");
                errorProvider1.Tag = 1;
            }
            if (cbScopeType.SelectedValue == null)
            {
                errorProvider1.SetIconAlignment(cbScopeType, ErrorIconAlignment.MiddleLeft);
                errorProvider1.SetError(cbScopeType, "Chưa loại scope");
                errorProvider1.Tag = 1;
            }

            if (string.IsNullOrEmpty(txtServerAssembly.Text))
            {
                errorProvider1.SetError(txtServerAssembly, "Chưa chọn Server Assembly");
                errorProvider1.Tag = 1;
            }
            if (string.IsNullOrEmpty(txtServerClassPath.Text))
            {
                errorProvider1.SetError(txtServerClassPath, "Chưa chọn Server Class");
                errorProvider1.SetIconAlignment(txtServerClassPath, ErrorIconAlignment.MiddleLeft);
                errorProvider1.Tag = 1;
            }
            if (string.IsNullOrEmpty(txtClientAssembly.Text))
            {
                errorProvider1.SetError(txtClientAssembly, "Chưa chọn Client Assembly");
                errorProvider1.Tag = 1;
            }
            if (string.IsNullOrEmpty(txtClientClassPath.Text))
            {
                errorProvider1.SetError(txtClientClassPath, "Chưa chọn Client Class");
                errorProvider1.SetIconAlignment(txtClientClassPath, ErrorIconAlignment.MiddleLeft);
                errorProvider1.Tag = 1;
            }
            if (errorProvider1.Tag != null)
            {
                MessageBox.Show("Lỗi nhập liệu");
                return;
            }
            try
            {

                SyncConfigDS.ScopeInfoExRow Scope = CurrentNode.Tag as SyncConfigDS.ScopeInfoExRow;
                bool isNew = false;
                if (Scope == null)
                {
                    //Update
                    isNew = true;
                    Scope = FrmMain.MainForm.TreeManipulation.dsSyncConfig.ScopeInfoEx.NewScopeInfoExRow();
                    Scope.ScopeExId = Guid.NewGuid();
                }

                Scope.ScopeName = txtScopeName.Text;
                Scope.Schema = txtSchema.Text;
                Scope.Comment = txtComment.Text;
                Scope.Direction = cbDirection.SelectedValue.ToString();
                // Scope.ClientID = cbClient.SelectedValue == null ? Guid.Empty : (Guid)cbClient.SelectedValue;
                Scope.ScopeType = (int)cbScopeType.SelectedValue;
                //Scope.Enable = ckEnable.Checked;
                //Scope.SkipDownloadFirst = ckSkipDownloadFirtRun.Checked;
                //Scope.SkipUploadFirst = ckSkipUploadFirst.Checked;
                Scope.ServerAssembly = txtServerAssembly.Text;
                Scope.ServerClass = txtServerClassPath.Text;
                Scope.ClientAssembly = txtClientAssembly.Text;
                Scope.ClientClass = txtClientClassPath.Text;
                Scope.ScopeVersion = txtScopeVersion.Value;
                Scope.SchemaVersion = txtSchemaVersion.Value;
                Scope.AssemblyVersion = txtAssemblyVersion.Value;
                //Scope.IsCommon = ckIsCommon.Checked;
                Scope.TemplateName = txtTemplate.Text;
                if (isNew)
                {
                    Scope.Ordinal = ADOSyncConfig.GetMaxOrdinal();
                    FrmMain.MainForm.TreeManipulation.dsSyncConfig.ScopeInfoEx.AddScopeInfoExRow(Scope);


                }
                FrmMain.MainForm.TreeManipulation.AdapterScopeInfoEx.Update(FrmMain.MainForm.TreeManipulation.dsSyncConfig.ScopeInfoEx);
                FrmMain.MainForm.TreeManipulation.dsSyncConfig.ScopeInfoEx.AcceptChanges();
                CurrentNode.Tag = Scope;
                DataView view = gridClient.PrimaryGrid.DataSource as DataView;
                if (isNew)
                {

                    foreach (DataRowView rowView in view)
                    {
                        rowView["ScopeExId"] = Scope.ScopeExId;
                        rowView["SyncTimes"] = 0;
                    }
                }
                if (view.Table.GetChanges() != null)
                {
                    foreach (DataRowView rv in view)
                        rv["ConfigTimes"] = rv["SyncTimes"];

                    FrmMain.MainForm.TreeManipulation.AdapterClientConfigTable.Update(view.Table as SyncConfigDS.ClientConfigDataTable);
                    view.Table.AcceptChanges();
                }

                Node parrentNode = CurrentNode;
                //if (!Scope.ClientID.Equals(Guid.Empty))
                //{
                //    parrentNode = FrmMain.MainForm.TreeManipulation.GetClientNode(Scope.ClientID);
                //}
                if (isNew)
                    parrentNode.Nodes.Add(FrmMain.MainForm.TreeManipulation.CreateSingleScopeNode(null, Scope));
                else
                    FrmMain.MainForm.TreeManipulation.CreateSingleScopeNode(parrentNode, Scope);

                Form frm = FindForm();
                if (frm.GetType().IsAssignableFrom(typeof(BaseDialog)))
                {
                    frm.DialogResult = DialogResult.OK;
                }
                else
                    MessageBox.Show("Dữ liệu đã được cập nhật");
            }
            catch (Exception ex)
            {
                FrmMain.MainForm.TreeManipulation.dsSyncConfig.ScopeInfoEx.RejectChanges();
                MessageBox.Show(ex.Message);
            }
        }

        private void txtServerAssembly_ButtonCustomClick(object sender, EventArgs e)
        {
            ChoiceAssembly(txtServerAssembly, "Choice Server Assembly");
        }
        void ChoiceAssembly(TextBoxX txtBox, string des)
        {
            OpenFileDialog ofdl = new OpenFileDialog();
            ofdl.Filter = "Dll file(*.dll)|*.dll|Execute file(*.exe)|*.exe|All file(*.*)|*.*";
            ofdl.InitialDirectory = Application.StartupPath;
            ofdl.Title = des;
            try
            {
                ofdl.ShowDialog();

                if (ofdl.FileName.Length > 0)
                {
                    string root = Application.StartupPath;
                    if (!root.EndsWith("\\"))
                        root += "\\";
                    Uri baseUri = new Uri(root);
                    Uri fileUri = new Uri(ofdl.FileName);
                    fileUri = baseUri.MakeRelativeUri(fileUri);
                    string relativePath = Uri.UnescapeDataString(fileUri.ToString());
                    txtBox.Text = relativePath.Replace("/", "" + Path.DirectorySeparatorChar);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                ofdl.Dispose();
            }

        }

        private void txtClientAssembly_ButtonCustomClick(object sender, EventArgs e)
        {
            ChoiceAssembly(txtClientAssembly, "Choice Client Assembly");
        }

        private void txtServerClassPath_ButtonCustomClick(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtServerAssembly.Text))
            {
                MessageBox.Show("Chọn Server assemble trước");
                return;
            }
            PickClass frm = new PickClass();
            frm.AssemblyPath = txtServerAssembly.Text;
            try
            {

                DialogResult result = frm.ShowDialog();
                if (result == DialogResult.OK)
                {
                    Type t = frm.SelectedRow["DataType"] as Type;
                    txtServerClassPath.Text = t.FullName;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                frm.Dispose();
            }
        }

        private void txtClientClassPath_ButtonCustomClick(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtClientAssembly.Text))
            {
                MessageBox.Show("Chọn Client assembly trước");
                return;
            }
            PickClass frm = new PickClass();
            frm.AssemblyPath = txtClientAssembly.Text;
            try
            {

                DialogResult result = frm.ShowDialog();
                if (result == DialogResult.OK)
                {
                    Type t = frm.SelectedRow["DataType"] as Type;
                    txtClientClassPath.Text = t.FullName;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                frm.Dispose();
            }
        }

        private void cbClient_ButtonCustomClick(object sender, EventArgs e)
        {
            AddClient frm = new AddClient();
            try
            {
                frm.New();
                frm.ShowDialog();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                frm.Dispose();
            }


        }


    }
}
